import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login.vue'
import BuyerHome from '../views/BuyerHome.vue'
import ProductList from '../views/ProductList.vue'

Vue.use(Router)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/buyer',
    component: BuyerHome,
    children: [
      {
        path: '',
        name: 'ProductList',
        component: ProductList
      },
      {
        path: 'orders',
        name: 'OrderHistory',
        component: () => import('../views/OrderHistory.vue')
      },
      {
        path: 'points',
        name: 'PointsHistory',
        component: () => import('../views/PointsHistory.vue')
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('../views/UserProfile.vue')
      },
      {
        path: 'messages',
        name: 'Messages',
        component: () => import('../views/Messages.vue')
      }
    ]
  },
  {
    path: '/',
    redirect: '/login'
  }
]

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')

  if (to.path === '/login') {
    if (token) {
      // 已登录，跳转到对应角色页面
      const user = JSON.parse(localStorage.getItem('user') || '{}')
      if (user.role === 'BUYER') {
        next('/buyer')
      } else if (user.role === 'SELLER') {
        next('/seller')
      } else {
        next()
      }
    } else {
      next()
    }
  } else if (to.path.startsWith('/buyer') || to.path.startsWith('/seller')) {
    if (!token) {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
